import { userList, userCount } from '@/request/api'

//封装一个接口数据类型
interface stateMember {
    list: Array<Object>,
    page: number,
    size: number,
    total: number
}


const state = {
    list: [],
    page: 1, //页码数
    size: 2,//查询条数
    total: 0, //总记录数
}

const getters = {
    getMember(state: stateMember) {
        return state.list
    },
    total(state: stateMember) {
        return state.total
    },
    size(state: stateMember) {
        return state.size
    }
}


const mutations = {
    mutationsList(state: stateMember, payload: any) {
        state.list = payload
    },
    changeTotal(state: stateMember, total: any) {
        state.total = total
    },
    changePage(state: stateMember, page: any) {
        // console.log(page);
        state.page = page
    }

}


const actions = {
    listActions(context: any) {
        let params = {
            page: context.state.page,
            size: context.state.size
        }
        userList(params).then((res: any) => {
            // console.log(res);
            if (res.code === 200) {
                if (res.list === null || res.list.length === 0) {
                    //当前页码数减一
                    let page = context.state.page - 1;
                    context.commit('changePage', page);
                    //再次更新  自调
                    context.dispatch('listActions');
                    return;
                }
            }
            context.commit('mutationsList', res.list)
        })
    },
    countActions(context: any) {
        //发起请求
        userCount().then((res: any) => {
            // console.log(res);
            if (res.code === 200) {
                context.commit('changeTotal', res.list[0].total)
            }
        })
    },
    pageActions(context: any, page: any) {
        context.commit('changePage', page)
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}